# Copyright (c) 2024-present AI-Labs

import subprocess
from fastapi import APIRouter, Request, HTTPException, Response
from fastapi.responses import FileResponse

import os
import re
import json
import torch
import numpy as np
import uuid
import soundfile

from configs import config

from datetime import datetime

from melotts.api import TTS


# 加载TTS模型
model = TTS(language="ZH", device="cpu")
speaker_ids = model.hps.data.spk2id

# 定义路由信息
router = APIRouter(
    prefix='/tts/melotts',
    tags = ['语音生成']
)

"""
文本转语音的具体实现过程
"""
def tts_to_file(input):
    # 指定本地路径
    localdir = f"audio/{datetime.now().strftime('%Y-%m-%d')}"
    os.makedirs(f"{config.setting.statics.path}/{localdir}", exist_ok=True)
    localfile = f"{localdir}/{uuid.uuid4()}.wav"

    # 将文本转换成语音并保存到本地文件
    model.tts_to_file(input, speaker_ids['ZH'], f"{config.setting.statics.path}/{localfile}", speed=0.7)

    # subprocess.getoutput(f"ffmpeg -i {localfile} -r 1 -t {image_limit} {imagedir}/image-%3d.jpg")

    return localfile


"""
对外暴露的文本转语音接口
"""
@router.post("/audio/speech")
def audio_speech(request: dict):
    # return FileResponse(tts_to_file(request["input"]), media_type="audio/wav")
    return {
                "data": {
                    "url": f"{config.setting.statics.urls}/{tts_to_file(request['input'])}"
                }
           }


"""
对外暴露的文本转语音接口
"""
@router.post("/generate_audio_url")
def generate_audio_url(request: dict):
    return f"{config.setting.statics.urls}/{tts_to_file(request['input'])}"


"""
对外暴露的文本转语音接口
"""
@router.post("/generate_audio_file")
def generate_audio_file(request: dict):
    return FileResponse(f"{config.setting.statics.path}/{tts_to_file(request['input'])}", media_type="audio/wav")
